package bidgetserver;

import java.io.IOException;
import java.util.Date;
import java.util.List;
//import java.util.List;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;
//import com.google.appengine.api.users.User;
//import com.google.appengine.api.users.UserService;
//import com.google.appengine.api.users.UserServiceFactory;

import bidgetserver.Product;
import bidgetserver.PMF;

public class AddUserProduct extends HttpServlet {
	//private static final Logger log = Logger.getLogger(AddUserProduct.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		//UserService userService = UserServiceFactory.getUserService();
		//User user = userService.getCurrentUser();
		boolean flag = true;
		boolean historyflag = false;
		String content = req.getParameter("content1");
		String userName = req.getParameter("userName");
		String ProductPicture = req.getParameter("ProductPic");
		String ProductName = req.getParameter("ProductName");
		String CellNum = req.getParameter("cellNum");
		String IsBuy = req.getParameter("isbuy");
		if(IsBuy==null){
			IsBuy="1";
			flag = false;
			content = req.getParameter("content3");
		}


		Date date = new Date();
		Product userHistory = new Product(userName, content, IsBuy, date, false,ProductPicture, ProductName, CellNum);
		PersistenceManager pm = PMF.get().getPersistenceManager();

		String query = "select from "+Product.class.getName()+" where author == '"+userName+"'";
        query+=" && ProductKey == '"+content+"'";
        query+=" && flag == false";
        List<Product> historyList = (List<Product>) pm.newQuery(query).execute();
        
        if(!historyList.isEmpty()){
        	historyflag = true;
        }
        
        
		try{
			if(historyflag == false){
				pm.makePersistent(userHistory);
			}
			if (flag==true){
				Product userProduct = new Product(userName, content, IsBuy, date, true, ProductPicture, ProductName,CellNum);
				pm.makePersistent(userProduct);
			}
		}
		finally{
			pm.close();
		}
	}
}
